﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CCL.Packet
{
    [Serializable]
    public abstract class PacketObject
    {
        /// <summary>
        /// ServiceType을 정합니다.
        /// </summary>
        public Packet.Service ServiceType { get; protected set; }

        /// <summary>
        /// Data의 길이를 정합니다.
        /// </summary>
        public int DataLength { get; protected set; }

        protected PacketObject(Packet.Service serviceType)
        {
            ServiceType = serviceType;
            DataLength = 0;
        }

        public static PacketObject Parse(byte[] byteArray)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();

            stream.Write(byteArray, 0, byteArray.Length);
            stream.Position = 0;

            CCL.Packet.PacketObject obj = formatter.Deserialize(stream) as CCL.Packet.PacketObject;

            return obj;
        }

        public byte[] GetByte()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(1024);

            formatter.Serialize(stream, this);

            byte[] byteArray = stream.GetBuffer();

            stream.Dispose();

            return byteArray;
        }
    }
}
